package POJO;

/**
 *
 * @author Sibrand
 */
import java.net.MalformedURLException;
import org.apache.commons.digester.rss.Channel;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.StringBufferInputStream;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.text.SimpleDateFormat;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.commons.digester.rss.Item;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class RSSCreator {

    private static String URL = "http://gwtgroep8.didactiek1.edm.uhasselt.be:8080/web/";
    private static String file = "/home/gwtgroep8/tomcat/web/feed.xml";

    public static void createRSS() throws IOException, MalformedURLException, ParserConfigurationException, SAXException {
        SimpleDateFormat formatter =
                new SimpleDateFormat("dd MMM yyyy HH:mm:ss Z");
        String today = formatter.format(new Date());

        Channel newChannel = new Channel();

        newChannel.setCopyright("(c)Hello World 2008");
        newChannel.setDescription("The most recently created trips.");
        newChannel.setTitle("Hello World, a Trip Content Manager");
        newChannel.setLink(URL);
        newChannel.setLanguage("en-us");
        newChannel.setPubDate(today);

        int[] trips = getTrips();

        for (int i = 0; i < trips.length; ++i) {

            Item item = new Item();
            item.setTitle(getName(trips[i]));
            item.setLink(getUrl(trips[i]));
            item.setDescription("(" + getStart(trips[i]) + " - " + getEnd(trips[i]) + ")");
            newChannel.addItem(item);
        }


        try {
            FileOutputStream fout = new FileOutputStream(file);
            newChannel.render(fout);
            fout.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static int[] getTrips() throws IOException, MalformedURLException, ParserConfigurationException, ParserConfigurationException, SAXException {

        String result[] = getResponseSoap("<mns1:getLatestTrips xmlns:mns1=\"http://Services/\"></mns1:getLatestTrips>");

        int[] r = new int[result.length];
        for (int i = 0; i < r.length; ++i) {
            r[i] = Integer.parseInt(result[i]);
        }
        return r;
    }

    private static String getUrl(int id) throws IOException, MalformedURLException, ParserConfigurationException, ParserConfigurationException, SAXException {

        String result[] = getResponseSoap("<mns1:getURL xmlns:mns1=\"http://Services/\"><tripId xsi:nil=\"true\">" + id + "</tripId></mns1:getURL>");

        if (result.length > 0) {
            return result[0];
        } else {
            return "";
        }
    }

    private static String getName(int id) throws IOException, MalformedURLException, ParserConfigurationException, ParserConfigurationException, SAXException {

        String result[] = getResponseSoap("<mns1:getName xmlns:mns1=\"http://Services/\"><tripId xsi:nil=\"true\">" + id + "</tripId></mns1:getName>");

        if (result.length > 0) {
            return result[0];
        } else {
            return "";
        }
    }

    private static String getEnd(int id) throws IOException, MalformedURLException, ParserConfigurationException, ParserConfigurationException, SAXException {

        String result[] = getResponseSoap("<mns1:getEnd xmlns:mns1=\"http://Services/\"><tripId xsi:nil=\"true\">" + id + "</tripId></mns1:getEnd>");

        if (result.length > 0) {
            return result[0];
        } else {
            return "";
        }
    }

    private static String getStart(int id) throws IOException, MalformedURLException, ParserConfigurationException, ParserConfigurationException, SAXException {

        String result[] = getResponseSoap("<mns1:getStart xmlns:mns1=\"http://Services/\"><tripId xsi:nil=\"true\">" + id + "</tripId></mns1:getStart>");

        if (result.length > 0) {
            return result[0];
        } else {
            return "";
        }
    }

    private static String[] getResponseSoap(String action) throws MalformedURLException, IOException, ParserConfigurationException, SAXException {
        URL u = new URL(URL + "tripData");
        URLConnection uc = u.openConnection();
        HttpURLConnection connection = (HttpURLConnection) uc;

        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("SOAPAction", "");
        connection.setRequestProperty("Content-Type", "text/xml; charset=UTF-8");

        OutputStream out = connection.getOutputStream();
        Writer wout = new OutputStreamWriter(out);

        wout.write("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?><SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:soap=\"http://schemas.xmlsoap.org/wsdl/soap/\" xmlns:tns=\"http://Services/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ><SOAP-ENV:Body>" + action + "</SOAP-ENV:Body></SOAP-ENV:Envelope>");
        wout.flush();
        wout.close();

        String response = "";
        InputStream in = connection.getInputStream();
        int c;
        while ((c = in.read()) != -1) {
            response += (char) c;
        }
        in.close();

        String jaxpPropertyName = "javax.xml.parsers.DocumentBuilderFactory";
        if (System.getProperty(jaxpPropertyName) == null) {
            String apacheXercesPropertyValue = "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl";
            System.setProperty(jaxpPropertyName, apacheXercesPropertyValue);
        }

        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = builderFactory.newDocumentBuilder();
        Document document = builder.parse(new StringBufferInputStream(response));
        document.getDocumentElement().normalize();
        Element rootElement = document.getDocumentElement();
        rootElement.normalize();

        NodeList friends = rootElement.getElementsByTagName("return");

        String[] result = new String[0];
        for (int i = 0; i < friends.getLength(); ++i) {

            result = addTo(result, new String[]{friends.item(i).getTextContent()});
        }
        return result;
    }

    private static String[] addTo(String[] s1, String[] s2) {
        String[] temp = new String[s1.length + s2.length];
        System.arraycopy(s1, 0, temp, 0, s1.length);
        System.arraycopy(s2, 0, temp, s1.length, s2.length);

        return temp;
    }
}
